package com.sk.skplanet.commute.fragments;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView.OnEditorActionListener;

import com.sk.skplanet.commute.R;
import com.sk.skplanet.commute.daofactory.LocalDaoFactory;

/**
 * A simple {@link android.support.v4.app.Fragment} subclass. Activities that
 * contain this fragment must implement the
 * {@link StopFirstSectionFragment.OnFragmentInteractionListener} interface to
 * handle interaction events. Use the
 * {@link StopFirstSectionFragment#newInstance} factory method to create an
 * instance of this fragment.
 * 
 */
public class StopFirstSectionFragment extends Fragment {
	// TODO: Rename parameter arguments, choose names that match
	// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
	private static final String ARG_PARAM1 = "param1";
	private static final String ARG_PARAM2 = "param2";

	// TODO: Rename and change types of parameters
	private String mParam1;
	private String mParam2;
	
	private List<String> stationNames;
	private List<String> stationCodes;
	
	private EditText searchTextStop;
	private ListView listView;
	private MyArrayAdapter adapter;

	private OnStopItemSelectedListener mListener;

	/**
	 * Use this factory method to create a new instance of this fragment using
	 * the provided parameters.
	 * 
	 * @param param1
	 *            Parameter 1.
	 * @param param2
	 *            Parameter 2.
	 * @return A new instance of fragment StopFirstSectionFragment.
	 */
	// TODO: Rename and change types and number of parameters
	public static StopFirstSectionFragment newInstance(String param1,
			String param2) {
		StopFirstSectionFragment fragment = new StopFirstSectionFragment();
		Bundle args = new Bundle();
//		args.putString(ARG_PARAM1, param1);
//		args.putString(ARG_PARAM2, param2);
		fragment.setArguments(args);
		return fragment;
	}

	public StopFirstSectionFragment() {
		// Required empty public constructor
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		stationNames = new ArrayList<String>();
		stationCodes = new ArrayList<String>();
		
		if (getArguments() != null) {
//			mParam1 = getArguments().getString(ARG_PARAM1);
//			mParam2 = getArguments().getString(ARG_PARAM2);
			
			
		}
		
		
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_stop_first_section, container,
				false);
		
		listView = (ListView)view.findViewById(R.id.stopSearchList);
		searchTextStop = (EditText)view.findViewById(R.id.searchTextStop);
		
		searchTextStop.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				search(s.toString());
			}
		});
		
		adapter = new MyArrayAdapter(getActivity());
		listView.setAdapter(adapter);
		
		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView av, View v, int i, long l) {
				TextView stopName = (TextView)v.findViewById(R.id.listview_search_bus_text_busno);
				TextView stopCode = (TextView)v.findViewById(R.id.listview_search_bus_text_bustype);
				
				mListener.onStopItemSelected(stopCode.getText().toString(), stopName.getText().toString());
			}
		});
		
		return view;
	}
	
	private void search(String arg) {
		stationNames.clear();
		stationCodes.clear();
		
		if(arg.length() > 0) {
			Cursor cursor = LocalDaoFactory.selectStationByStopCode(arg);
			
			if(cursor != null && cursor.getCount() != 0) {
				cursor.moveToFirst();
				
				while(!cursor.isAfterLast()) {
					stationNames.add(cursor.getString(cursor.getColumnIndex("stationNameKor")));
					stationCodes.add(cursor.getString(cursor.getColumnIndex("stationId")));
					cursor.moveToNext();
				}
			} else {
				// 검색결과 없음처리.
			}
		}
		adapter.notifyDataSetChanged();
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		try {
			mListener = (OnStopItemSelectedListener) activity;
		} catch (ClassCastException e) {
			throw new ClassCastException(activity.toString()
					+ " must implement OnFragmentInteractionListener");
		}
	}

	@Override
	public void onDetach() {
		super.onDetach();
		mListener = null;
	}

	public interface OnStopItemSelectedListener {
		public void onStopItemSelected(String arsId, String arsName);
	}
	
	private class MyArrayAdapter extends ArrayAdapter {
		Context context;
		
		MyArrayAdapter(Context context) {
			super(context, R.layout.listview_search_bus_info, stationNames);
			
			this.context = context;
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			LayoutInflater inflater = ((Activity) context).getLayoutInflater();
			
			View row = (View)inflater.inflate(R.layout.listview_search_bus_info, null);
			
			TextView stopName = (TextView)row.findViewById(R.id.listview_search_bus_text_busno);
			TextView stopCode = (TextView)row.findViewById(R.id.listview_search_bus_text_bustype);
			
			stopName.setText(stationNames.get(position));
			stopCode.setText(stationCodes.get(position));
			
			return row;
		}
	}

}
